<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <div class="uploadcon">
        <span v-if="!imageUrl">上传图片</span>
        <div v-else>
          <img :src="imageUrl" alt="" />
        </div>
      </div>
    </el-upload>
    <i class="el-icon-circle-close" @click="clearImg"></i>
  </div>
</template>

<script>
export default {
  props: ['imageUrl'],
  methods: {
    upload (file) {
      var COS = require('cos-js-sdk-v5')

      // SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
      var cos = new COS({
        SecretId: 'AKID2HJ4XkhNlsiGXYIlyuc4F9m8D0XnmTt3',
        SecretKey: 'vZw2rOeeMnxqRlob8j48uPdZEdlcDXaL'
      })
      cos.putObject(
        {
          Bucket: 'web68-1308716109' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: file.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: file.file // 上传文件对象
        },
        (err, data) => {
          console.log(err || data)
          this.imageSrc = 'https://' + data.Location
          this.$emit('update:imageUrl', this.imageSrc)
        }
      )
    },
    clearImg () {
      this.$emit('update:imageUrl', '')
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.uploadcon {
  width: 96px;
  height: 58px;
  position: absolute;
  padding: 10px 19px;
  border: 1px dashed gray;
  border-radius: 7px;
  margin-left: 390px;
  margin-top: -70px;
}
.uploadcon img {
  width: 96px;
  height: 58px;
  position: absolute;
  top: -1px;
  left: -1px;
}
.el-icon-circle-close {
  position: relative;
  top: -95px;
  right: -475px;
  font-size: 20px;
  cursor: pointer;
}
</style>
